<?php
namespace app\admin\controller;
use think\facade\View;
use think\facade\Request;
use think\facade\Db;
use think\facade\Session;

class Liberum extends Common{

    //公海列表
    public function index(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_customer')
                ->where(['status'=>2,'issuccess'=>-1])
                ->order('id desc')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            // 是否有查看手机号的权限
            $userinfo = Db::name('admin')->where('username',$this->admin['username'])->find(); 
            if ($userinfo['isphone'] == 0) {
                foreach ($list['data'] as $key => $value) {
                    $value['phone'] = mb_substr($value['phone'], 0, 3).'****'. mb_substr($value['phone'], 7, 11);
                    $list['data'][$key] = $value;
                }
            }
            
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }

        $ghTypeList = Db::table('crm_liberum_type')->select();
        //技术QQ1147361223
        $more=$this->system['more'];
        if($more['kfrecycleday']>0){
        //    说明启用了客服回收 to_kh_time

            $kfrecycledaytime=date('Y-m-d H:i:s',strtotime("-{$more['kfrecycleday']} day"));
            Db::table('crm_customer')->where("`status`=1 and `to_kh_time` < '{$kfrecycledaytime}' and `last_up_time` < '{$kfrecycledaytime}'")->update(['status'=>2,'to_gh_time'=>date("Y-m-d H:i:s",time())]);
        }


        View::assign('ghTypeList',$ghTypeList);

        return View::fetch();
    }


    //公海类型
    public function libTypeList(){
        if($this->request->isPost()){
            $page =input('page',1,'intval');
            $pageSize =input('limit',config('app.pageSize'),'intval');
            $list = \think\facade\Db::name('crm_liberum_type')
                ->paginate(['list_rows'=>$pageSize,'page'=>$page])
                ->toArray();
            return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);
        }
        return View::fetch('liberum/lib_type_list');
    }
    //添加公海类型
    public function libTypeAdd(){
        if($this->request->isPost()){
            $data['type_name'] = Request::param('type_name');
            $data['add_time'] = time();
            $result = Db::table('crm_liberum_type')->insert($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'添加成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'添加失败！','data'=>[]];
                return json($msg);
            }
        }
        return View::fetch('liberum/lib_type_add');
    }
    //编辑公海类型
    public function libTypeEdit(){
        if ($this->request->isAjax()){
            
            $data  = $this->request->post();
            $result = Db::table('crm_liberum_type')->where(['id'=>$data['id']])->update($data);
            if ($result){
                $msg = ['code' => 0,'msg'=>'编辑成功！','data'=>[]];
                return json($msg);
            }else{
                $msg = ['code' => -200,'msg'=>'编辑失败！','data'=>[]];
                return json($msg);
            }
        }
        $result = Db::table('crm_liberum_type') ->where(['id' => Request::param('id')])->find();
        View::assign('result',$result);
        return View::fetch('liberum/lib_type_edit');
    }
    //删除公海类型
    public function libTypeDel(){
        $id = Request::param('id');
        $result = Db::table('crm_liberum_type')->where('id',$id)->delete();
        if ($result){
            $msg = ['code' => 0,'msg'=>'删除成功！','data'=>[]];
            return json($msg);
        }else{
            $msg = ['code' => -200,'msg'=>'删除失败！','data'=>[]];
            return json($msg);
        }
    }


    //公海搜索
    public function liberumSearch(){
        $page =input('page',1,'intval');
        $limit =input('limit')?input('limit'):config('app.pageSize');
        $keyword = Request::param('keyword');
        $liberumModel=new \app\admin\model\liberum();
        $list=  $liberumModel -> getLiberumSearchList($page,$limit,$keyword);
        return json(['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1]);

    }

    //写跟进
    public function libdialog(){
        $result = Db::table('crm_customer')->where(['id'=>Request::param('id')])->find();

        $result['comment']= Db::table('crm_comment')->alias('com')->join('admin adm','com.user_id = adm.admin_id')->where(['customer_id'=>Request::param('id')])->field('com.*,adm.username,adm.avatar')->select();
        foreach ($result['comment'] as $k => $v){
            $result['comment'][$k]['reply'] = Db::table('crm_reply')->where(['comment_id'=>$v['id']])->select();
        }

        View::assign('result',$result);
        return View::fetch('liberum/libdialog');
    }
    //抢客户
    public function robClient(){
        $data['id'] = $this->request->param('id');
//        技术QQ1147361223 开启事务,防止2人同时抢造成混乱
        $res=$this->getGrabCount();
        if(!$res['code']){
            $msg = ['code' => -200,'msg'=>$res['msg'],'data'=>[]];
            return json($msg);
        }

        Db::startTrans();
        try {
        //然后查询的时候加锁,
            //抢客户之前，先去判断是否可抢
            $gh_client = Db::table('crm_customer')->where(['id' => $data['id']])->where(['status'=> 2])->lock(true)->find();
            if ($gh_client){
                $data['to_kh_time'] = time();
                $data['status'] = 1;//0-线索，1客户，2公海
//                $data['pr_user_bef'] = $gh_client['pr_user'];
                $data['pr_user'] = $this->admin['username'];
                
                //是否有效客资 重置 状态
                $data['yx_status'] = -1;
                $data['wx_remark'] = '';
                
                $result = Db::table('crm_customer')->where(['id'=>$data['id']])->update($data);
                Db::table('crm_grab')->insert(['admin_id'=>$this->admin['admin_id'],'customer_id'=>$data['id'],'createtime'=>time()]);
                if ($result){
                    Db::commit();
                    $result = ['code' => 1, 'msg' => '抢客户成功！'];
                    return json($result);
                }else{
                    throw new \Exception('抢客户失败！', -200);
                }
            }else{
                throw new \Exception('抱歉，该客户已被抢走！', -200);

            }

        }catch (\Throwable $t){
            Db::rollback();
            $msg = ['code' => $t->getCode(),'msg'=>$t->getMessage(),'data'=>[]];
            return json($msg);
        }catch (\Exception $e){
            Db::rollback();
            $msg = ['code' => $e->getCode(),'msg'=>$e->getMessage(),'data'=>[]];
            return json($msg);
        }


    }



}
